<?php

namespace app\mfw_order\controller;

use think\Db;
require_once EXTEND_PATH.'newMfw-sdk/Openapi.php';

class MfwOrder
{

    public $count = 1;
    /**
     * 构造函数
     * MfwComment constructor.
     */
    public function __construct(){}

    /**
     *  子进程启动时触发
     * @param $worker
     */
    public function onWorkerStart($worker){
        echo "马蜂窝订单子进程启动了\n";
        if($worker->id === 0 || $worker->id === 1){
            \workerman\Lib\Timer::add(10,[$this, 'timeTask']); // 定时器
        }
//        if($worker->id === 3){
//            \workerman\Lib\Timer::add(30,[$this, 'dealComment']); // 定时器
//        }
    }

    /**
     * 连接时触发
     * @param $connection
     */
    public function onConnect($connection){
        echo "连接成功\n";
        $connection->send('<h2 style="color: #4288ce;font-size: 20px">hello!</h2>');
    }

    /**
     *  接收到消息时触发
     * @param $connection
     * @param $message
     */
    public function onMessage($connection, $message) {
        var_dump($message);
        $connection->send("<span style='color: #000088;'>很高兴和你认识</span>\n");
    }

    /**
     *  连接关闭时触发
     * @param $connection
     */
    public function onClose($connection){
        echo "连接断开了\n";
    }

    /**
     *  worker进程停止时触发
     * @param $connection
     */
    public function onWorkerStop($connection){
        echo "正在重启!\n";
    }


    /**
     *  从马蜂窝平台获取订单信息
     */
    public function timeTask($page_no = 1)
    {
        echo "定时任务\n";
        $action = 'sales.order.list.get'; // 调用接口
        $data = [];
        $data['page_no'] = 1; // 业务请求数据
        // 实例化请求
        $obj = new \MSDK_Php_Openapi(); // 创建对象
        // 请求接口
        if (false == $obj->send($action,$data)){
            $msg['status'] = false;
            $msg['error_id'] = 1905051424;
            $msg['msg'] = '接口调用失败';
            $msg['get_msg'] = $obj->getError();
            $msg['get_error'] = $obj->getErrno();
            logs('MfwOrderList', $msg);
        }else{
            $total = $obj->getData()['total'];
            $result =  $obj->getData()['list'];
            if ($result){
                // 处理马蜂窝订单
                self::saveMfwOrder($result);
            }
        }
    }

    /**
     *  把马蜂窝订单保存进数据表里面
     */
    public static function saveMfwOrder($data = [])
    {
        if (!empty($data) && count($data) > 1){
            foreach ($data as $index => $datum) {
                $find = Db::name('mfw_booking_people')->where('mfw_order_id',$datum['orderId'])->find();
                if ($find){
                    continue;
                }
                $saveData = [];
                $people = [];
                if (!empty($datum['bookingPeople'])){
                    $people = [
                        'uid' => $datum['bookingPeople']['uid'],
                        'name' => $datum['bookingPeople']['name'],
                        'email' => $datum['bookingPeople']['email'],
                        'mfw_order_id' => $datum['orderId'],
                        'phone_area' => $datum['bookingPeople']['phone_area'],
                        'phone' => $datum['bookingPeople']['phone'],
                        'wechat' => $datum['bookingPeople']['wechat'],
                        'remark' => $datum['bookingPeople']['remark'],
                    ];
                }
                $mfw_booking_people_id = Db::name('mfw_booking_people')->strict(false)->insertGetId($people);
                $saveData['order_id'] = $datum['orderId'];
                $saveData['order_status'] = $datum['status']['orderStatus'];
                $saveData['refund_status'] = $datum['status']['refundStatus'];
                $saveData['all_refund_flag'] = $datum['status']['allRefundFlag'];
                $saveData['go_date'] = ($datum['goDate'] == '0000-00-00')?'':strtotime($datum['goDate']);
                $saveData['end_date'] = ($datum['endDate'] == '0000-00-00')?'':strtotime($datum['endDate']);
                $saveData['paytime'] = ($datum['paytime'] == '0000-00-00')?'':strtotime($datum['paytime']);
                $saveData['ctime'] = ($datum['ctime'] == '0000-00-00')?'':strtotime($datum['ctime']);
                $saveData['mfw_booking_people_id'] = $mfw_booking_people_id;
                $saveData['sales_id'] = $datum['salesId'];
                $saveData['sales_name'] = $datum['salesName'];
                $saveData['ota_sales_name'] = $datum['otaSalesName'];
                $saveData['sales_type'] = $datum['salesType'];
                $saveData['mdd'] = $datum['mdd'];
                $saveData['from'] = $datum['from'];
                $saveData['sku_id'] = $datum['skuId'];
                $saveData['ota_sku_id'] = $datum['otaSkuId'];
                $saveData['sku_name'] = $datum['skuName'];
                $saveData['total_price'] = $datum['totalPrice'];
                $saveData['payment_fee'] = $datum['paymentFee'];
                $saveData['create_time'] = time();
                $saveData['items'] = json_encode($datum['items'],JSON_UNESCAPED_UNICODE);
                $saveData['promotion_detail'] = json_encode($datum['promotionDetail'],JSON_UNESCAPED_UNICODE);
                $saveData['skus'] = json_encode($datum['skus'],JSON_UNESCAPED_UNICODE);
                $saveData['data'] = json_encode($datum,JSON_UNESCAPED_UNICODE);
                // 存进数据表
                Db::name('mfw_order')->strict(false)->insert($saveData);
                // 把马蜂窝的订单同步到订单表中
                $saveData['people'] = $datum['bookingPeople'];
                $saveData['reduce_ota'] = $datum['promotionDetail']['reduce_ota'];
                $saveData['reduce_mfw'] = $datum['promotionDetail']['reduce_mfw'];
                self::saveOrder($saveData);
            }
        }
    }



    /**
     *  同步订单
     */
    public static function saveOrder($data = [])
    {
        if (!empty($data)){
            if (!in_array($data['order_status'],[1,2,4])){
                return false;
            }
            if (!in_array($data['all_refund_flag'],[0,1])){
                return false;
            }
            if (in_array( $data['refund_status'],[1,2,4])){
                return false;
            }
            $find = Db::name('order')->where('order_id',$data['order_id'])->find();
            if ($find){
                return false;
            }
            $saveData = [];
            $saveData['order_id'] = $data['order_id'];
            $saveData['order_status'] = $data['order_status'];
            $saveData['money'] = $data['payment_fee'];
            $saveData['title'] = $data['sales_name'];
            $saveData['platform'] = 'mfw';
            $saveData['start_time'] =$data['go_date'];
            $saveData['end_time'] =$data['end_date'];
            $saveData['booking_people_name'] =$data['people']['name'];
            $saveData['booking_people_email'] =$data['people']['email'];
            $saveData['booking_people_phone'] =$data['people']['phone'];
            $saveData['booking_people_wechat'] =$data['people']['wechat'];
            $saveData['booking_people_remark'] =$data['people']['remark'];
            $saveData['booking_people_phone_area'] =$data['people']['phone_area'];
            $saveData['uid'] =$data['people']['uid'];
            $saveData['sales_id'] =$data['sales_id'];
            $saveData['ctime'] =$data['ctime'];
            $saveData['sku_id'] =$data['sku_id'];
            $saveData['sales_name'] =$data['sales_name'];
            $saveData['sku_name'] =$data['sku_name'];
            $saveData['total_price'] =$data['total_price'];
            $saveData['payment_fee'] =$data['payment_fee'];
            $saveData['reduce_ota'] =$data['reduce_ota'];
            $saveData['reduce_mfw'] =$data['reduce_mfw'];
            $saveData['ota_sales_name'] =$data['ota_sales_name'];
            $saveData['dispose_status'] ='no_contact';
            // 保存到订单表
            Db::name('order')->strict(false)->insert($saveData);
        }
    }

}